package com.onpositive.simple.persistance;

import java.util.ArrayDeque;
import java.util.BitSet;

public class RAMRecordStorage extends RecordStorage {
	
	private int recordStorage[] ;
	
	int recordsCount ;
	
	private ArrayDeque<Integer> emptyCells ;
	private BitSet deletedFlag ; 

	public RAMRecordStorage(  )
	{
		int primalRecordscount = 5 ;
		recordStorage = new int[ primalRecordscount ] ;
		emptyCells = new ArrayDeque<Integer>() ;
		deletedFlag = new BitSet() ;
		recordsCount = 0 ;
	}
	
	@Override
	public int putRecord( int[] record) {
		
		int id = getVacantId() ;
		
		deletedFlag.set( id, false ) ;
		recordsCount++ ;
		putRecord(record, id) ;		
		
		return id ;
		
	}
	
	@Override
	protected int getVacantId()
	{
		Integer emptyCell = emptyCells.pollFirst() ;
		
		if ( emptyCell == null ){
			
			for( ; recordStorage.length < recordLength*(recordsCount+1) ; )
				reallocateStarage() ;
			emptyCell = recordsCount ;
		}
		
		return emptyCell ;
	}	
	
	@Override
	protected void putRecord( int[] record, int id )
	{
		int startIndex = id*recordLength ; 
		for( int i = 0 ; i < recordLength ; i++ )
			recordStorage[ startIndex+i ] = record[i] ;
	}
		
	@Override
	public int[] getRecord(int id) {
		
		if( !deletedFlag.get(id) ){

			int record[] = new int[recordLength] ;
			
			int startIndex = recordLength*id ;

			for( int i = 0 ; i < recordLength ; i++ )
				record[i] = recordStorage[ startIndex+i ] ;
			
			return record ;	
		}
			
					
		return null;
	}
	
	@Override
	public void deleteRecord(int id) {
		if( !deletedFlag.get(id) )
		{
			deletedFlag.set(id, true) ;
			emptyCells.add(id) ;			
		}		
	}
	
	private void reallocateStarage()
	{
		int tmpStorage[] = new int[ (int)(recordStorage.length * 1.4) ] ;
		for( int i = 0 ; i < recordStorage.length ; i++  )
			tmpStorage[i] = recordStorage[i] ;
		
		recordStorage = tmpStorage ;		
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		
	}

	



	
}
